package com.xinsmartsky.penmaji.SerialPort;

import android.util.Log;

import com.friendlyarm.AndroidSDK.HardwareControler;
import com.xinsmartsky.penmaji.penmaji.SerialPortActivity;

import java.util.ArrayList;

import static java.lang.Thread.sleep;

/**
 * Created by wangxiao on 16-1-25.
 * 从串口中读取数据块
 */
public class ReadSerialData implements Runnable {
    private static final int BUFSIZE = 512;
    private static byte[] buf = new byte[BUFSIZE];
    private static byte[] send_buf = new byte[1];
    static ReadSerialData rsd = new ReadSerialData();
    private int devfd = -1;
    boolean flag = true;
    private ArrayList<Byte> SerialData = new ArrayList<Byte>();//动态数组
    private FileOperation fileOperation;
    private SerialPortActivity sendserial = new SerialPortActivity();
    //字节数组  //动态数组到普通数组的转换？？？？

    private boolean bianhao = true;
    private int crc_add = 0;
    private int count = 0;
    private boolean ChaoShi = true;
    private boolean readdata = true;
    private int second = 5000;

    private boolean readfile = false;

    public ReadSerialData(int devfd) {
        this.devfd = devfd;
    }

    public ReadSerialData() {
        ;
    }

    //取出地址上的数据
    public byte GetDataFromAdress(int address) {
        byte[] getbytearray = new byte[]{};
        getbytearray = fileOperation.ReadDataFromFile("serialdatablock.txt");
        if (getbytearray.length > 0) {
            int posi = (address - 0x400 + 1);
            byte getdata = getbytearray[posi];
            return getdata;
        }
        return -1;
    }

    private int hujiaosignal = 0;
    int aaa = 0;

    //修改数据
    @Override
    public void run() {
        while (flag) {
//            Log.i("fd", "读线程...");
            if (ChaoShi) {
                second = 0;
            } else {
                second = 5000;
            }
            if (HardwareControler.select(devfd, 0, second) == 1) {
                int retsize = HardwareControler.read(devfd, buf, BUFSIZE);
                if (retsize > 0) {
                    aaa += retsize;
                    if (retsize == 1 && buf[0] == 0x59) {
                        send_buf[0] = (byte) 0xa7;
                        HardwareControler.write(devfd, send_buf);
                        Log.i("fd", "reply OK");
                        readfile = true;
                        hujiaosignal = 59;
                    } else {
                        if (hujiaosignal == 59) {
//                            Log.i("fd", "接收到数据块");
                            for (count = 0; count < retsize; count++) {
                                if (bianhao) {
                                    crc_add += buf[count];
                                    SerialData.add(buf[count]);
                                    bianhao = false;
                                } else {
                                    crc_add += buf[count];
                                    SerialData.add(buf[count]);//放到动态数组中
                                }
                            }
                        } else {
                            Log.i("fd", "没有呼叫的数据块");
                        }
                    }
                }
                ChaoShi = false;
            } else {
                if (count > 0 && (SerialData.size() > 0) && (hujiaosignal == 59)) {
                    hujiaosignal = 0;//必须先呼叫才能发数据块
                    String getcrc = "";
                    String str_crc_add = "";
                    crc_add -= buf[count - 1];
                    str_crc_add = Integer.toHexString((byte) crc_add & 0x000000ff);
                    crc_add = 0;
                    getcrc = Integer.toHexString(buf[count - 1] & 0x000000ff);
                    Log.i("fd", "取到的累加和:" + getcrc + "      计算的累加和 " + str_crc_add);
                    //计算数据块校验和
                    if (getcrc.equalsIgnoreCase(str_crc_add)) {
                        send_buf[0] = (byte) 0x0f;
                    } else {
                        send_buf[0] = (byte) 0xf0;
                    }
                    int wri = HardwareControler.write(devfd, send_buf);
                    if (wri > 0) {
                        Log.i("fd", "回复了" + Integer.toHexString(send_buf[0] & 0x000000ff));
                        count = 0;
                    }
                    fileOperation = new FileOperation();
                    //转化为普通数组
                    byte[] temparray = new byte[SerialData.size()];
                    for (int index = 0; index < SerialData.size(); index++) {
                        temparray[index] = SerialData.get(index);
                    }
                    SerialData.clear();//回复后使缓冲区里的内容清零
                    while (readfile) {
                        if (fileOperation.WriteDataToFile(temparray, "serialdatablock.txt")) {
                            int len = (fileOperation.ReadDataFromFile("serialdatablock.txt")).length;
                            Log.i("fd", "文件路径：" + fileOperation.getFilePath() + "  大小：" + len);
                            //打印读到的数据
                            fileOperation.PrintData();//显示收到的数据块+++++++++++++++++++++++++++++++
                            readfile = false;
                        } else {
                            Log.i("fd", "将数据块写入文件中失败");
                            readfile = false;
                        }
                    }
                    ChaoShi = true;
//                        flag = false;
                } else {
                    Log.i("fd", "没有回复×××××××××××××××××××××××××××××××");
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void start() {
        flag = true;
    }

    public void shutdown() {
        flag = false;
    }
}
